<template>
<div class="user-manage">
  <a-tabs default-active-key="1" v-model="activeKey" @change="callback">
    <a-tab-pane key="0" tab="本店图库">
      <search-form-table 
        :url="url"
        isApiSearch
        ref="ourSearchtable" 
        :columns="columns" 
        :form="form" 
        :xLength="1800"
        :defaultParams="{
          seriesType: 0
        }">
        <template slot="searchForm">
          <a-form layout="inline" :form="form">
            <a-form-item label="套系名称">
              <a-input
                v-decorator="[
                  'title',
                ]"
                placeholder="请输入套系名称"
              >
              </a-input>
            </a-form-item>
            <a-form-item label="上传日期">
              <fast-range-picker
                v-decorator="[
                  'startTime-endTime',
                ]"
                >
              </fast-range-picker>
            </a-form-item>
            <a-form-item label="是否展示">
              <a-select style="width: 180px" v-decorator="['enableShow']"  
                placeholder="全部" 
                :options="whetherOptions">
              </a-select>
            </a-form-item>
            <a-form-item label="是否为新品">
              <a-select style="width: 180px" v-decorator="['enableNew']"  
                placeholder="全部" 
                :options="whetherOptions">
              </a-select>
            </a-form-item>
          </a-form>
        </template>
        <template slot="oprationRow">
          <a-space>
            <permission authority="gallery:productpublish:add" v-if="shopType == 1">
              <a-button type="primary" @click="publishStore($refs.ourSearchtable.selectedRowKeys)">发布到门店</a-button>
            </permission>
            <permission authority="gallery:product:add">
              <a-button type="primary" icon="plus" @click="openNew({}, 1)">新增套系</a-button>
            </permission>
          </a-space>
        </template>
        <template slot="tableOperation" slot-scope="{record}">
          <a-space>
            <a href="javascript:;" class="text-primary pointer" @click="openProList(record)">套系产品</a>
            <permission authority="gallery:product:modify">
              <a href="javascript:;" class="text-primary pointer" @click="openNew(record, 2)">编辑</a>
            </permission>
            <permission authority="gallery:product:delete">
              <a href="javascript:;" class="text-danger" @click="deleteRows(record)">删除</a>
            </permission>
            <permission authority="gallery:productpublish:add" v-if="shopType == 1">
              <span class="text-primary pointer" @click="publishStore([record.id])">发布到门店</span>
            </permission>
          </a-space>
        </template>
      </search-form-table>
    </a-tab-pane>
    <a-tab-pane key="1" tab="其他店图库">
      <search-form-table 
          :url="url"
          isApiSearch
          ref="otherSearchtable" 
          :columns="columns" 
          :form="form" 
          :xLength="1800"
          :defaultParams="{
            seriesType: 1
          }">
        <template slot="searchForm">
          <!-- 分店不展示这两个 -->
          <a-form layout="inline" :form="form">
            <!-- <a-form-item label="机构名称">
              <a-input
                v-decorator="[
                  'orgName',
                ]"
                placeholder="请输入机构名称"
              >
              </a-input>
            </a-form-item>
            <a-form-item label="店铺名称">
              <a-input
                v-decorator="[
                  'shopName',
                ]"
                placeholder="请输入店铺名称"
              >
              </a-input>
            </a-form-item> -->
            <a-form-item label="套系名称">
              <a-input
                v-decorator="[
                  'title',
                ]"
                placeholder="请输入套系名称"
              >
              </a-input>
            </a-form-item>
            <a-form-item label="上传日期">
              <fast-range-picker
                v-decorator="[
                  'startTime-endTime',
                ]"
                >
              </fast-range-picker>
            </a-form-item>
            <a-form-item label="是否展示">
              <a-select style="width: 180px" v-decorator="['enableShow']"  
                placeholder="全部" 
                :options="whetherOptions">
              </a-select>
            </a-form-item>
            <a-form-item label="是否为新品">
              <a-select style="width: 180px" v-decorator="['enableNew']"  
                placeholder="全部" 
                :options="whetherOptions">
              </a-select>
            </a-form-item> 
          </a-form>
        </template>
        <template slot="tableOperation" slot-scope="{record}">
          <a-space>
            <a href="javascript:;" class="text-primary pointer" @click="openProList(record)">套系产品</a>
            <permission authority="gallery:product:modify">
              <a href="javascript:;" class="text-primary pointer" @click="openNew(record, 3)">查看</a>
            </permission>
            <permission authority="gallery:product:delete" v-if="shopType == 1">
              <a href="javascript:;" class="text-danger" @click="deleteRows(record)">删除</a>
            </permission>
            <a-switch :checked="record.enableUse == 1" v-else @change="onEnableUseChange(record)" />
          </a-space>
        </template>
      </search-form-table>
    </a-tab-pane>
  </a-tabs>
  <!-- 新增、编辑、查看套系 -->
  <NewSerises 
    ref="newSerises" 
    :shopType="shopType" 
    :opration="opration" 
    :record="currentRecord" 
    @cancel="closeNewModal" 
    :visible="newVisible">
  </NewSerises>
  <!-- 产品详情 -->
  <ProductDetail 
    :record="currentRecord" 
    @cancel="closeInfoModal" 
    :visible="infoVisible">
  </ProductDetail>
  <!-- 门店列表 -->
  <ShopList 
    ref="ShopListRef" 
    :visible="publishVisible" 
    :shopIds="shopIds" 
    @cancel="publishVisible = false" 
    @submit="handleShopSubmit">
  </ShopList>
</div>
</template>
<script>
import NewProducts from './components/NewProducts'
import NewSerises from './components/NewSerises'
import ProductDetail from './components/ProductDetail'
import PostToStore from './components/PostToStore'
import { showPlatformList } from '@/utils/dictData'
import ShopList from '@/components/ShopList/ShopList';
import SearchFormTable from '@/components/ShopList/SearchFormTable';

export default {
  name: 'Role',
  data () {
    return {
      url: '/gallery/series/page',
      statusUrl:'/gallery/series/enable',
      newVisible: false,
      infoVisible: false,
      publishVisible: false,
      currentRecord: {},
      form: this.$form.createForm(this, { name: 'table_search' }),
      columns: [
        {
          title: '套系图片',
          dataIndex: 'cover',
          key: 'cover',
          align: 'center',
          customRender: (text, row) => {
            return <table-img src={text}/>
          }
        },
        {
          title: '套系标题',
          dataIndex: 'title',
          key: 'title'
        },
        {
          title: '所属分类',
          dataIndex: 'seriesClassificationName',
          key: 'seriesClassificationName',
          width: 200
        },
        {
          title: '排序',
          dataIndex: 'sort',
          key: 'sort',
          align: 'center'
        },
        {
          title: '展示平台',
          dataIndex: 'exhibitionPlatform',
          key: 'exhibitionPlatform',
          customRender: (text, row) => {
            let arr = text && text.split(',')
            let tmpData = []
            arr.forEach(val => {
              tmpData.push(this.getPlatformName(val))
            })
            return tmpData.join('/')
          }
        },
        {
          title:'是否展示',
          dataIndex:'enableShow',
          key:'enableShow',
          customRender: (text, record) => < a-switch checked={text == 1} onChange={() => this.onEnableShowChangeShow(record, text)} />,
        },
        {
          title:'设为新品',
          dataIndex:'enableNew',
          key:'enableNew',
          customRender: (text, record) => < a-switch checked={text == 1} onChange={() => this.onIsNewChangeShow(record, text)} />,
        },
        {
          title: '所属机构',
          dataIndex: 'orgName',
          key: 'orgName',
          align: 'center'
        },
        {
          title: '所属店铺',
          dataIndex: 'shopName',
          key: 'shopName',
          align: 'center'
        },
        {
          title: '上传员工',
          dataIndex: 'createByName',
          key: 'createByName',
          align: 'center'
        },
        {
          title: '创建时间',
          dataIndex: 'createDate',
          key: 'createDate'
        },
        {
          title: '最后保存时间',
          dataIndex: 'updateDate',
          key: 'updateDate'
        },
        {
          title: '操作',
          fixed: "right",
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      seriesIds:'',
      shopIds:[],
      whetherOptions: [
        {label: '是', value: 1},
        {label: '否', value: 0}
      ],
      activeKey: '0',
      opration: '1', //操作类型 1、新增套系 2、编辑套系 3、查看套系
    }
  },
  components: {
    NewProducts,
    NewSerises,
    ProductDetail,
    PostToStore,
    ShopList,
    SearchFormTable
  },
  computed:{
    userInfo(){
      return this.$store.getters.userInfo || {};
    },
    shopId(){
      return this.userInfo.shopId || '';
    },
    shopType(){
      //总店1；分店2；供应商3
      if(this.$route.query.shopType) return this.$route.query.shopType;
      if(this.userInfo.shopRoleCode=='role:store:main'){
        return 1;
      }
      else if(this.userInfo.shopRoleCode=='role:store:branch'){
        return 2;
      }
      else if(this.userInfo.shopRoleCode=='role:supplier'){
        return 3;
      }
    },
    // 本店搜索
    searchKey() {
      return this.activeKey == '0' ? 'ourSearchtable' : 'otherSearchtable'
    }
  },
  methods: {
    callback(key) {
      if (key == '0') {
        this.$nextTick(() => {
          this.$refs.ourSearchtable.resetForm();
        });
      } else {
        this.$nextTick(() => {
          this.$refs.otherSearchtable.resetForm();
        });
      }
    },
    // 通过value展示名
    getPlatformName (value) {
      return showPlatformList.map(item => {
        if (item.value == value) {
          return item.label
        }
      }).filter(item => {
        return item
      })
    },
    async handleSwitch(status,row){
      console.log(status,row)
    },
    // 发布到门店
    publishStore (ids) {
      if(ids.length==0){
        this.$message.error('请选择套系产品')
        return;
      }
      this.seriesIds = ids;
      this.publishVisible = true
    },
    closeInfoModal (freshTable) {
      this.infoVisible = false
      if (freshTable) {
        this.$refs[this.searchKey].refreshTable()
      }
    },
    // 设为新品
    async changeShow(params) {
      let res = await this.$post(this.statusUrl, params);
      if (res && res.returnCode === 1000) {
        this.$message.success('操作成功!')
        this.$refs[this.searchKey].refreshTable();
      }
    },
    onEnableUseChange(record) {
      this.changeShow({
        id: record.id,
        gallerySeriesType: this.activeKey,
        enableUse: record.enableUse == 0 ? 1 : 0
      });
    },
    // 是否展示
    onEnableShowChangeShow(record, text) {
      this.changeShow({
        id: record.id,
        gallerySeriesType: this.activeKey,
        enableShow: text == 1 ? 0 : 1,
      });
    },
    // 是否新品
    onIsNewChangeShow(record, text) {
      if(!record.enableShow){
        this.$message.error('请先打开展示状态!')
        return
      }
      this.changeShow({
        id: record.id,
        gallerySeriesType: this.activeKey,
        enableNew: text == 1 ? 0 : 1
      });
    },
    openInfo (record) {
      this.currentRecord = record
      this.infoVisible = true
    },
    closeNewModal (freshTable, publishInfo = null) {
      this.newVisible = false
      if (freshTable) {
        this.$refs[this.searchKey].refreshTable()
      }
      console.log(publishInfo)
      if(publishInfo) {
        this.seriesIds = [publishInfo.seriesIds];
        this.publishVisible = true;
      }
    },
    openProList(record) {
      this.$router.push({
        name: "GalleryLibraryManagementSeriesProList",
        params: {
          ...record,
          seriesType: this.activeKey
        }
      });
    },
    openNew(record, type) {
      this.$refs.newSerises.resetData(); //清除弹窗之前的数据
      this.opration = type;
      this.newVisible = true;
      this.currentRecord = record;
    },
    closePublishModal (freshTable) {
      this.publishVisible = false
      if (freshTable) {
        this.$refs[this.searchKey].refreshTable();
      }
    },
    // 发布到门店
    async handleShopSubmit(shopIds){
      let res = await this.$post('/gallery/seriespublish/add',{
        shopIds,
        seriesIds: this.seriesIds
      })
      this.$refs.ShopListRef.confirmLoading = false;
      if(res && res.returnCode=='1000'){
        this.publishVisible = false;
        this.seriesIds = [];
        this.$message.success('发布成功！');
      }
    },
    // 套系只能单个删除
    deleteRows (record) {
			if (!record.id) return this.$message.warn('请先选择一项后再进行操作');
      this.$confirm({
        title: '删除提示',
        content: '删除操作不可恢复，请确认是否删除？',
        okText: '确认删除',
        cancelText: '取消',
        onOk: () => {
          this.$post('/gallery/series/delete', { id: record.id, shopId: record.shopId }).then(res => {
            if (res && res.returnCode == 1000) {
              this.$message.success('删除成功')
              this.$refs[this.searchKey].refreshTable();
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>

</style>
